package com.axend.aerosense.user.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModel;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.user.entity.LoginDevInfoBean;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.user.R;
import com.axend.aerosense.user.UserSettingActivity;
import com.axend.aerosense.user.databinding.UserSafeCheckFragmentBinding;

import io.reactivex.disposables.Disposable;


public class SafeCheckFragment extends MvvmBaseFragment<UserSafeCheckFragmentBinding, ViewModel> {
    public static final String ARG_PARAM = "ARG_PARAM";
    private CountDownTimer timer;
    private LoginDevInfoBean bean;
    private Disposable disposable = null;

    public static SafeCheckFragment getInstance(LoginDevInfoBean bean){
        SafeCheckFragment fragment = new SafeCheckFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_PARAM, bean);
        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if(bundle != null){
            bean = (LoginDevInfoBean) bundle.getSerializable(ARG_PARAM);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
//        if(null != bean){
//            deleteDev(getActivity());
//        }


    }
    @Override
    public void onResume() {
        super.onResume();
        ((UserSettingActivity)getActivity()).setTitle(getString(R.string.user_safe_check));
        if(timer != null){
            timer.cancel();
        }
        timer = new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if(null != bean){
                    deleteDev(getActivity(), bean, new IOperationResult() {
                        @Override
                        public void onSuccess() {
                            FragmentManager.BackStackEntry entry = getActivity().getSupportFragmentManager().getBackStackEntryAt(2);
                            int id = entry.getId();
                            getActivity().getSupportFragmentManager().popBackStack(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.LOGIN_DEV_CHANGE, Boolean.class).postValue(true);
                        }

                        @Override
                        public void onFail() {
                            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.LOGIN_DEV_CHANGE, Boolean.class).postValue(false);
                        }
                    });
                }


            }
        };
        timer.start();
    }

    @Override
    public void onPause() {
        if(null !=timer){
            timer.cancel();
            timer = null;
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        if(null !=timer){
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    @Override
    public int getLayoutId() {
        return R.layout.user_safe_check_fragment;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected ViewModel getViewModel() {
        return null;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    public void deleteDev(Activity activity, LoginDevInfoBean bean, IOperationResult operationResult){
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        if(TextUtils.isEmpty(token)){
            return;
        }
        disposable = EasyHttp.post(UrlApi.URL.DelLoginDevInfo.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(operationResult != null){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        if(operationResult != null){
                            operationResult.onSuccess();
                        }
                    }
                });
    }

}
